﻿Imports MindFusion.Scheduling
Imports MindFusion.Scheduling.WinForms
Imports System.Drawing.Drawing2D

Public Class frmPlanning
    Public pTypePlanning

    Private szSQL As String
    Private rs As ADODB.Recordset
    Private centered As StringFormat

    Private Sub frmPlanning_Load(sender As Object, e As System.EventArgs) Handles Me.Load

        ' définir l'orientation du texte
        centered = New StringFormat
        centered.Alignment = StringAlignment.Center
        centered.LineAlignment = StringAlignment.Center
        Me.BackColor = getSocieteColor()

        rb_JOURNEE.Checked = True     ' affichage par journée
        ' initialiser la date à aujourd'hui
        TE_DATE.Value = Format(Now, "yyyy/MM/dd")
        ' affichage à la journée
        CAL_PLANNING.CurrentView = CalendarView.ResourceView
        CAL_PLANNING.GroupType = GroupType.GroupByResources
        CAL_PLANNING.Date = TE_DATE.Value
        CAL_PLANNING.EndDate = CAL_PLANNING.Date.AddHours(23)
        CAL_PLANNING.CurrentTime = CAL_PLANNING.Date
        CAL_PLANNING.ResourceViewSettings.TimelineScale = 190
        CAL_PLANNING.ResourceViewSettings.BottomTimelineSettings.Format = "H:mm"
        TE_CODE_ITC.Clear()
        LoadPlanning()

    End Sub

    ' Load le planning par Journée
    Sub LoadPlanning()
        Dim noResource As Integer = 0

        Me.Cursor = Cursors.WaitCursor
        ' effacer la sélection
        CAL_PLANNING.Selection.Reset()
        CAL_PLANNING.ResetDrag()
        ' effacer le calendrier
        CAL_PLANNING.Schedule.Clear()
        CAL_PLANNING.Resources.Clear()

        Dim resource As Resource = Nothing

        If rb_JOURNEE.Checked = True Then
            ' Affichage par journée, disposer les ITCs présents en coordonnées
            szSQL = "CALL spGET_AGENDAS('" & pTypePlanning & "')"
            GetRecordset(ctDSN_DEVFAC, szSQL, rs)

            Do While Not rs.EOF
                resource = New Resource
                resource.Name = rs.Fields("nom").Value
                resource.Id = rs.Fields("code").Value
                CAL_PLANNING.BeginInit()
                ' créer la ressource ITC
                CAL_PLANNING.Resources.Add(resource)
                ' ajouter les RDV de la journée dans le planning
                LoadRendezVous(CAL_PLANNING.Date, CAL_PLANNING.EndDate, resource.Id, noResource)
                CAL_PLANNING.EndInit()
                ' save 1er ITC trouvé
                If TE_CODE_ITC.TextLength = 0 Then
                    TE_CODE_ITC.Text = resource.Id
                    TE_NOM_ITC.Text = resource.Name
                End If
                rs.MoveNext()
                noResource = noResource + 1
            Loop
            rs.Close()
            resource = Nothing
        Else
            CAL_PLANNING.BeginInit()
            ' Affichage par semaine, disposer les heures en coordonnées
            LoadRendezVous(CAL_PLANNING.Date, CAL_PLANNING.EndDate, TE_CODE_ITC.Text, noResource)
            CAL_PLANNING.EndInit()
            ' positionner le planning sur 6h
            CAL_PLANNING.VScrollPos = 5
        End If
        Me.Cursor = Cursors.Default

    End Sub

    Private Sub LoadRendezVous(ByVal debut As Date, ByVal fin As Date, ByVal szCode_ITC As String, ByVal noResource As Integer)
        Dim rsRDV As ADODB.Recordset = Nothing
        Dim app As Appointment

        ' Lire la journée du planning
        szSQL = "CALL spGet_PLANNING_byITC('" & Format(debut, "yyyy/MM/dd") & "','" & Format(fin, "yyyy/MM/dd") & "','" & szCode_ITC & "')"
        GetRecordset(ctDSN_DEVFAC, szSQL, rsRDV)

        Do While Not rsRDV.EOF
            app = New Appointment()
            Dim jour As Date = rsRDV.Fields("datevi").Value
            Dim heure As Date = rsRDV.Fields("heurevi").Value
            app.StartTime = New Date(jour.Year, jour.Month, jour.Day, heure.Hour, heure.Minute, 0)
            app.EndTime = app.StartTime.AddMinutes(60)
            app.HeaderText = Mid(rsRDV.Fields("c_nom").Value, 1, 15)
            If rb_JOURNEE.Checked = True Then
                app.Resources.Add(CAL_PLANNING.Resources(noResource))
            End If
            app.Tag = rsRDV.Fields("rubrique").Value
            app.Id = rsRDV.Fields("societe").Value & "-" & rsRDV.Fields("no_id").Value

            ' colorier la cellule selon la societe
            Dim bcolor As MindFusion.Drawing.SolidBrush

            Select Case rsRDV.Fields("societe").Value
                Case "PE"
                    bcolor = New MindFusion.Drawing.SolidBrush(Color.LightYellow)
                Case "ME"
                    bcolor = New MindFusion.Drawing.SolidBrush(Color.Gold)
                Case "PL"
                    bcolor = New MindFusion.Drawing.SolidBrush(Color.LightGreen)
                Case "PO"
                    bcolor = New MindFusion.Drawing.SolidBrush(Color.LightBlue)
                Case Else
                    bcolor = New MindFusion.Drawing.SolidBrush(Color.White)
            End Select

            If rb_JOURNEE.Checked = True Then
                app.Style.HeaderBrush = bcolor
            Else
                app.Style.Brush = bcolor
            End If
            app.AllowChangeEnd = False
            app.AllowChangeStart = False
            app.AllowMove = False
            app.AllDayEvent = False
            CAL_PLANNING.Schedule.Items.Add(app)
            rsRDV.MoveNext()
        Loop
        ' Close the recordset AND connection.
        rsRDV.Close()


    End Sub

    Private Sub BO_PREC_Click(sender As System.Object, e As System.EventArgs) Handles BO_PREC.Click

        If rb_JOURNEE.Checked Then
            TE_DATE.Value = CAL_PLANNING.Date.AddDays(-1)
            'End If
            rb_JOURNEE_Click(sender, e)
        Else
            ' recule le planning de 7 jours
            TE_DATE.Value = CAL_PLANNING.Date.AddDays(-7)
            rb_SEMAINE_Click(sender, e)
        End If

    End Sub

    Private Sub BO_SUIVANT_Click(sender As System.Object, e As System.EventArgs) Handles BO_SUIVANT.Click

        If rb_JOURNEE.Checked Then
            ' avance le planning d'un jour
            TE_DATE.Value = CAL_PLANNING.Date.AddDays(1)
            'End If
            rb_JOURNEE_Click(sender, e)
        Else
            ' avance le planning de 7 jours
            TE_DATE.Value = CAL_PLANNING.Date.AddDays(7)
            rb_SEMAINE_Click(sender, e)
        End If

    End Sub

    Private Sub rb_JOURNEE_Click(sender As Object, e As System.EventArgs) Handles rb_JOURNEE.Click

        ' affichage par Journée
        CAL_PLANNING.CurrentView = CalendarView.ResourceView
        CAL_PLANNING.GroupType = GroupType.GroupByResources
        CAL_PLANNING.ResourceViewSettings.TimelineScale = 190
        CAL_PLANNING.ResourceViewSettings.BottomTimelineSettings.Format = "H:mm"
        CAL_PLANNING.Date = Format(TE_DATE.Value, "yyyy/MM/dd")
        CAL_PLANNING.EndDate = CAL_PLANNING.Date.AddHours(23)
        CAL_PLANNING.CurrentTime = TE_DATE.Value
        LoadPlanning()

    End Sub

    Private Sub rb_SEMAINE_Click(sender As Object, e As System.EventArgs) Handles rb_SEMAINE.Click

        Dim i As Integer

        If TE_CODE_ITC.Text.Length = 0 Then
            MsgBox("Sélectionner d'abord un des moniteurs en cliquant sur son nom.")
            Exit Sub
        End If

        ' affichage sur 6 jours
        CAL_PLANNING.CurrentView = CalendarView.Timetable
        CAL_PLANNING.GroupType = GroupType.None
        CAL_PLANNING.TimetableSettings.Dates.Clear()
        CAL_PLANNING.Date = getLundiPrecedent(TE_DATE.Value)
        For i = 0 To 5
            CAL_PLANNING.TimetableSettings.Dates.Add(CAL_PLANNING.Date.AddDays(i))
        Next i
        CAL_PLANNING.EndDate = CAL_PLANNING.Date.AddDays(5)

        CAL_PLANNING.CurrentTime = TE_DATE.Value
        LoadPlanning()

    End Sub

    Private Sub TE_DATE_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles TE_DATE.KeyDown

        If e.KeyCode = Keys.Return Then
            TE_DATE_LostFocus(sender, e)
        End If

    End Sub

    Private Sub TE_DATE_LostFocus(sender As Object, e As System.EventArgs) Handles TE_DATE.LostFocus

        ' si affichage par Journée, traiter les changements de date
        If rb_JOURNEE.Checked Then
            ' dimanche ?
            If TE_DATE.Value.DayOfWeek = 0 Then
                TE_DATE.Value.AddDays(1)
            End If
            rb_JOURNEE_Click(sender, e)
        Else
            rb_SEMAINE_Click(sender, e)
        End If

    End Sub

    Private Sub CAL_PLANNING_DateClick(sender As Object, e As MindFusion.Scheduling.WinForms.ResourceDateEventArgs) Handles CAL_PLANNING.DateClick
        MsgBox("A faire", MsgBoxStyle.Information)
    End Sub

    Private Sub CAL_PLANNING_Draw(sender As Object, e As MindFusion.Scheduling.WinForms.DrawEventArgs) Handles CAL_PLANNING.Draw

        Dim bounds As Rectangle = e.Bounds
        Dim g As MindFusion.Drawing.IGraphics = e.Graphics
        Dim r As Resource = e.Resource
        Dim Jour As Date = e.Date

        Select Case e.Element
            Case CustomDrawElements.ResourceViewRowHeader
                ' encadrer les nom des ressources
                g.FillRectangle(Brushes.White, e.Bounds)
                g.DrawString(r.Name, e.Style.HeaderFont, Brushes.Navy, _
                             New RectangleF(e.Bounds.X, e.Bounds.Y, e.Bounds.Width, e.Bounds.Height), centered)
                g.DrawLine(Pens.Gray, e.Bounds.Left, e.Bounds.Bottom - 1, e.Bounds.Right - 1, e.Bounds.Bottom - 1)
                ' tracer une ligne sur bordure gauche
                g.DrawLine(Pens.Gray, e.Bounds.Right - 1, e.Bounds.Top, e.Bounds.Right - 1, e.Bounds.Bottom)

            Case CustomDrawElements.ResourceViewCell
                ' colorier la colonne
                Dim bcolor As Brush = Brushes.White
                If Jour.DayOfWeek = CAL_PLANNING.FirstWeekendDay Then
                    ' week-end
                    bcolor = Brushes.LightGray
                ElseIf IsHoliday(Jour) Then
                    ' jour férié 
                    bcolor = Brushes.LightSalmon
                End If
                If IsDayOff(Jour) = True Then
                    ' jour de repos du moniteur ?
                    bcolor = Brushes.LightGray
                End If
                g.FillRectangle(bcolor, bounds)
                ' tracer une ligne sur bordure gauche
                g.DrawLine(Pens.Gray, e.Bounds.Right - 1, e.Bounds.Top, e.Bounds.Right - 1, e.Bounds.Bottom)

        End Select

        If CAL_PLANNING.CurrentView = CalendarView.Timetable Then
            bounds.Inflate(-1, -1)
            If IsDayOff(Jour.AddHours(e.StartTime.Hours)) = True Then
                ' jour de repos du moniteur ?
                e.Graphics.FillRectangle(Brushes.LightGray, bounds)
            Else
                e.Graphics.FillRectangle(Brushes.White, bounds)
            End If
            ' colorier les cellules selon les horaires : travail = blanc, non travail = fumée blanc
            If Jour = DateTime.Now.Date Then
                ' date du jour
                e.Graphics.FillRectangle(Brushes.Orange, bounds)
            ElseIf Jour.DayOfWeek = CAL_PLANNING.FirstWeekendDay Then
                ' week-end
                e.Graphics.FillRectangle(Brushes.LightGray, bounds)
            ElseIf IsHoliday(Jour) Then
                ' jour férié 
                e.Graphics.FillRectangle(Brushes.LightSalmon, bounds)
            End If
        End If

    End Sub

    Private Sub CAL_PLANNING_ItemClick(sender As Object, e As MindFusion.Scheduling.WinForms.ItemMouseEventArgs) Handles CAL_PLANNING.ItemClick

        If System.Windows.Forms.MouseButtons.Left Then
            ' Get the clicked event
            Dim app As Appointment = e.Item 'as Appointment

            ' le rendez-vous appartient à la société ?
            If app.Id.Substring(0, 2) <> gSocieteCode Then
                MsgBox("Ce rendez-vous n'appartient pas à cette sociéte. Consultation impossible.", MsgBoxStyle.Critical)
                Exit Sub
            End If
            ' afficher les détails 
            Select Case app.Tag
                Case "DD"
                    frmDemandeDevis.pRubrique = "DEM_DEVIS"
                    frmDemandeDevis.pNoDossier = app.Id.Substring(3)
                    frmDemandeDevis.ShowDialog()
                Case "RV"
                    frmDemandeDevis.pRubrique = "RDVOUS"
                    frmDemandeDevis.pNoDossier = app.Id.Substring(3)
                    frmDemandeDevis.ShowDialog()
                Case "OS"
                    frmOrdreService.pNoDossier = app.Id.Substring(3)
                    frmOrdreService.ShowDialog()
                Case Else

            End Select
        End If

    End Sub

    Private Sub CAL_PLANNING_ResourceViewRowHeaderClick(sender As Object, e As MindFusion.Scheduling.WinForms.ResourceDateEventArgs) Handles CAL_PLANNING.ResourceViewRowHeaderClick
        TE_CODE_ITC.Text = e.Resource.Id    ' Moniteur sélectionné
        TE_NOM_ITC.Text = e.Resource.Name
    End Sub

    Function IsDayOff(ByVal Jour As Date) As Boolean

        IsDayOff = True

        ' cette heure est-elle horsAff de ses horaires de travail ?
        If Jour.Hour < 8 Or (Jour.Hour >= 12 And Jour.Hour < 14) Or Jour.Hour >= 18 Then
            Exit Function
        End If

        IsDayOff = False

    End Function

    Private Sub BO_EDITER_Click(sender As System.Object, e As System.EventArgs) Handles BO_EDITER.Click

    End Sub

End Class